package com.sevennotes.classtable.ui.pages.editstudent

import androidx.compose.animation.*
import androidx.compose.foundation.*
import androidx.compose.foundation.gestures.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowRight
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import com.sevennotes.classtable.config.Config
import com.sevennotes.classtable.config.MIN_TIME_MINUTE
import com.sevennotes.classtable.config.Settings
import com.sevennotes.classtable.model.StudentItem
import com.sevennotes.classtable.model.Time
import com.sevennotes.classtable.ui.pages.components.*
import com.sevennotes.classtable.ui.pages.main_screen.EditStudentState
import com.sevennotes.classtable.utils.TimeUtil
import java.lang.Exception

@ExperimentalComposeUiApi
@Composable
fun EditStudentPage(
  editStudentState: EditStudentState,
  changeStudentInfo: (StudentItem) -> Unit,
  onUpdateClass: (Int, Int, Time, Int) -> Unit,
  onAddClass: (Int, Int, Time, Int) -> Unit,
  onDeleteClass: (Int) -> Unit,
  gotoGpRecord: (Int) -> Unit,
  gotoClassAmountRecord: (Int) -> Unit
) {
  var timeSelectorVisiable by remember { mutableStateOf(false) }
  var selectClassIndex by remember { mutableStateOf(-1) }
  var onNoteVisible by remember { mutableStateOf(false) }
  val student = editStudentState.student
  val keyboard = LocalSoftwareKeyboardController.current
  val focusor = LocalFocusManager.current
  Surface(
    modifier = Modifier
      .fillMaxSize()
  ) {
    Column(
      Modifier
        .fillMaxHeight()
        .background(color = MaterialTheme.colors.background)
        .verticalScroll(rememberScrollState())
        .pointerInput(Unit) {
          forEachGesture {
            detectTapGestures(
              onTap = {
                keyboard?.hide()
                focusor.clearFocus()
              }
            )
          }
        }
    ) {
      StudentNameContainer(
        textValue = student.name,
        onNameChanged = { changeStudentInfo(student.copy(name = it)) },
        onNoteClick = {
          keyboard?.hide()
          onNoteVisible = !onNoteVisible
        }
      )
      AnimatedVisibility(visible = onNoteVisible) {
        //备注信息
        Column {
          OutlinedTextField(
            modifier = Modifier
              .fillMaxWidth()
              .padding(10.dp),
            value = student.note,
            onValueChange = { changeStudentInfo(student.copy(note = it)) }
          )
          Divider(color = Config.dividerColor)
          CheckButton(
            modifier = Modifier.padding(horizontal = 10.dp),
            checked = !student.usable,
            onCheckedChange = {
              changeStudentInfo(student.copy(usable = !it))
            },
            text = "学生已停课"
          )
        }
      }
      Spacer(modifier = Modifier.height(5.dp))
      StudentColorPicker(student.color) { changeStudentInfo(student.copy(color = it)) }
      Spacer(modifier = Modifier.height(5.dp))
      ItemCell(
        modifier = Modifier.clickable { gotoGpRecord(student.id ?: -1) }
      ) {
        Text(text = "当前积分", modifier = Modifier.weight(1f))
        Text(text = "${student.gradePoint} 分")
        Icon(imageVector = Icons.Filled.KeyboardArrowRight, contentDescription = null)
      }
      ItemCell(
        modifier = Modifier.clickable { gotoClassAmountRecord(student.id ?: -1) }
      ) {
        Text(text = "剩余课时", modifier = Modifier.weight(1f))
        Text(text = "${student.classAmount} 节")
        Icon(imageVector = Icons.Filled.KeyboardArrowRight, contentDescription = null)
      }
      Spacer(modifier = Modifier.height(5.dp))
      editStudentState.classList.forEachIndexed { index, it ->
        val text = TimeUtil.conversionTimeToString(it.startTime, it.duration, it.weekDay)
        ClassTimeContainer(
          text = text,
          currentIndex = index,
          onTimePadClicked = {
            keyboard?.hide()
            timeSelectorVisiable = true
            selectClassIndex = index
          },
          onDeleteClicked = {
            if (timeSelectorVisiable) {
              timeSelectorVisiable = false
            } else {
              onDeleteClass(it)
            }
          }
        )
      }
      AddItemCell {
        keyboard?.hide()
        onAddClass(student.id ?: -1, 0, Time(8, 0), 40)
      }
    }
    AnimatedVisibility(
      visible = timeSelectorVisiable,
      enter = slideIn { IntOffset(0, it.height) },
      exit = slideOut { IntOffset(0, it.height) },
    ) {
      val selectedClass = editStudentState.classList[selectClassIndex]
      TimePickerDialog(
        modifier = Modifier.wrapContentHeight(align = Alignment.Bottom),
        list = Settings.getClassChoiceList(),
        picked = listOf(
          selectedClass.weekDay,
          Settings.hours.indexOf(selectedClass.startTime.startHour),
          Settings.minutes.indexOf(selectedClass.startTime.startMin),
          Settings.durations.indexOf(selectedClass.duration)
        ),
        onCancelClick = { timeSelectorVisiable = false},
        onConfirmClick = {
          try {
            onUpdateClass(
              selectClassIndex,
              it[0],
              Time(
                Settings.hours[it[1]],
                Settings.minutes[it[2]]
              ),
              Settings.durations[it[3]]
            )
          }catch (e: Exception) {
            timeSelectorVisiable = false
          }
          timeSelectorVisiable = false
        }
      )
    }
  }
}

@Composable
fun StudentColorPicker(
  color: Int? = null,
  onColorChange: (Int) -> Unit
) {
  val colors = createColorMap()
  fun radomColor(): Int {
    return colors.shuffled().take(1)[0]
  }

  val selected = color ?: radomColor()
  if (color == null) {
    SideEffect { onColorChange(selected) }
  }
  var colorPicker by remember { mutableStateOf(false) }
  fun border(selected: Boolean) = if (selected) Modifier.border(1.dp, Color.White) else Modifier
  Column(
    modifier = Modifier
      .fillMaxWidth()
      .padding(horizontal = 10.dp)
  ) {
    Row(
      verticalAlignment = Alignment.CenterVertically
    ) {
      Box(
        modifier = Modifier
          .height(40.dp)
          .weight(1f)
          .background(color = Color(selected), shape = RoundedCornerShape(5.dp))
          .padding(horizontal = 10.dp)
          .clickable { onColorChange(radomColor()) }
      )
      Spacer(modifier = Modifier.width(20.dp))
      Button(onClick = { colorPicker = !colorPicker }) {
        Text(text = "选择颜色")
      }
    }
    AnimatedVisibility(visible = colorPicker) {
      Spacer(modifier = Modifier.height(5.dp))
      Row(
        modifier = Modifier
          .fillMaxWidth()
          .horizontalScroll(rememberScrollState()),
        horizontalArrangement = Arrangement.Center,
        verticalAlignment = Alignment.CenterVertically
      ) {
        colors.forEach {
          Box(
            modifier = border(selected == it)
              .size(40.dp)
              .background(color = Color(it))
              .clickable { onColorChange(it) }
          )
        }
      }
    }
    Divider(color = Config.dividerColor)
  }
}

@Composable
fun StudentNameContainer(
  textValue: String,
  onNameChanged: (String) -> Unit,
  onNoteClick: () -> Unit
) {
  ItemCell {
    OutlinedTextField(
      modifier = Modifier
        .weight(1f)
        .focusable(),
      value = textValue,//editStudentState.student?.name ?: "",
      singleLine = true,
      colors = TextFieldDefaults.textFieldColors(
        backgroundColor = MaterialTheme.colors.background,
        cursorColor = contentColorFor(backgroundColor = MaterialTheme.colors.background),
        focusedIndicatorColor = contentColorFor(backgroundColor = MaterialTheme.colors.background),
      ),
      onValueChange = onNameChanged,//onStudentNameChanged,
      label = { Text(text = "学生姓名") },
    )
    Spacer(modifier = Modifier.width(15.dp))
    Button(onClick = onNoteClick) {
      Text(text = "备注信息")
    }
  }
}

@Composable
fun ClassTimeContainer(
  modifier: Modifier = Modifier,
  currentIndex: Int,
  text: String,
  onTimePadClicked: () -> Unit,
  onDeleteClicked: (Int) -> Unit
) {
  ItemCell(modifier = modifier) {
    Row(verticalAlignment = Alignment.CenterVertically) {
      IconButton(
        onClick = { onDeleteClicked(currentIndex) }
      ) {
        Icon(
          imageVector = Icons.Outlined.Delete,
          contentDescription = "delete"
        )
      }
      Box(
        modifier = Modifier
          .fillMaxSize()
          .clickable { onTimePadClicked() },
        contentAlignment = Alignment.CenterStart
      ) { Text(text = text) }
    }
  }
}


@Preview(showBackground = true)
@Composable
fun ClassTimeContainerPrev() {
  ClassTimeContainer(text = "12:00 -- 13:00", currentIndex = 1, onTimePadClicked = { }) {

  }
}

@Preview(showBackground = true)
@Composable
fun StudentNameContainerPrev() {
  StudentNameContainer(
    textValue = "张三",
    onNameChanged = {},
    onNoteClick = {})
}